﻿using System;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;
using xuni;

namespace xres
{

    public class CopyFileAction : BaseAsyncAction
    {

        public const string Err_Copy = "Err_Copy";


        string _srcPath = "";
        string _dstPath = "";
        bool _isMove = false;


        public void Copy(string srcPath, string dstPath, bool move)
        {
            //对象可用于重复执行copy任务
            switch (_state)
            {
            case BaseAsyncActionState.Init:
            case BaseAsyncActionState.Finish:
                break;

            default:
                return;
            }

            _srcPath = srcPath;
            _dstPath = dstPath;
            _isMove = move;

            _state = "InCopy";

            ThreadPool.QueueUserWorkItem(CopyOnThread);
        }

        void CopyOnThread(object state)
        {
            if (false) Debug.Log($"CopyFile: {_srcPath} => {_dstPath}");

            var errMsg = "";
            try
            {
                /*
                var buffer = _buffer;

                using (var srcFs = File.OpenRead(_srcPath))
                using (var dstFs = File.OpenWrite(_dstPath))
                {
                    srcFs.Seek(0, SeekOrigin.End);
                    _totalBytes = srcFs.Position;
                    srcFs.Seek(0, SeekOrigin.Begin);

                    var len = 0;
                    while ((len = srcFs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        dstFs.Write(buffer, 0, len);
                        _haveCopyBytes += len;
                    }
                }
                */
                if (_isMove)
                {
                    if (File.Exists(_dstPath))
                        File.Delete(_dstPath);

                    File.Move(_srcPath, _dstPath);
                }
                else
                {
                    File.Copy(_srcPath, _dstPath, true);
                }

                errMsg = "";
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                Debug.Log($"file copy fail: {ex.Message}");
            }

            MainThreadSync.QueueOnMainThread(OnComplete_Copy, 0, errMsg);
        }

        void OnComplete_Copy(UserData userData)
        {
            if (false) Debug.Log($"CopyFile: OnComplete_Copy: {_srcPath}");

            var errMsg = userData.s;

            if (!string.IsNullOrEmpty(errMsg))
            {
                SetError(Err_Copy, errMsg);
                SetFinishAndNotify(ErrMsg);
            }
            else
            {
                SetError("", "");
                SetFinishAndNotify("");
            }
        }


    } //end of class


}


